package com.earthea.application.task.impl;

import com.earthea.application.task.TaskService;
import com.earthea.application.task.entity.Task;
import com.earthea.application.task.entity.TaskConstants;
import com.earthea.application.task.entity.TaskStatus;
import com.earthea.application.task.mysql.TaskRepository;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.PostConstruct;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskRepository taskRepository;

    @PostConstruct
    public void init() {
        taskRepository.create();
    }

    @Override
    public int addTask(List<Task> tasks) {
        return taskRepository.batchAddTask(tasks);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public List<Task> poll(String type, String label, int limit) {
        List<Task> tasks = taskRepository.poll(type, label, TaskStatus.INIT.getStatus(), limit);
        if (CollectionUtils.isEmpty(tasks)) {
            return Lists.newArrayList();
        }
        tasks.forEach(task -> task.setStatus(TaskStatus.INT_PROCESS.getStatus()));
        int update = taskRepository.batchUpdateToProcessing(tasks);
        if (update == tasks.size()) {
            return tasks;
        }
        return poll(type, label, limit);
    }

    @Override
    public int updateTask(List<Task> tasks) {
        return taskRepository.batchUpdateTask(tasks);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int archiving(int limit) {
        List<Task> tasks = taskRepository.queryByHistory(TaskConstants.DEFAULT_ARCHIVING_LIMIT);
        taskRepository.batchDelete(tasks);
        return taskRepository.batchAddHistory(tasks);
    }

    @Override
    public int retryProcessing(String updateTime, int limit) {
        return taskRepository.batchUpdateProcessing(updateTime, limit);
    }

    @Override
    public void createHistory(String tableName) {
        taskRepository.createHistory(tableName);
    }
}
